<template>
  <view class="drugs-container">
    <!-- 搜索区域 -->
    <view class="search-section">
      <view class="search-box">
        <view class="search-input-wrapper">
          <text class="iconfont icon-search search-icon"></text>
          <input 
            type="text" 
            v-model="searchKeyword"
            placeholder="搜索药品名称、成分、适应症"
            class="search-input"
            @input="onSearchInput"
            @confirm="searchDrugs"
          />
          <view class="clear-btn" v-if="searchKeyword" @click="clearSearch">
            <text class="iconfont icon-close"></text>
          </view>
        </view>
        <button class="ocr-btn" @click="showOCROptions">
          <text class="iconfont icon-camera"></text>
          识别
        </button>
      </view>
      
      <!-- 搜索历史 -->
      <view class="search-history" v-if="showSearchHistory && searchHistory.length > 0">
        <view class="history-header">
          <text class="history-title">搜索历史</text>
          <view class="clear-history" @click="clearSearchHistory">
            <text class="iconfont icon-delete"></text>
            清空
          </view>
        </view>
        <view class="history-tags">
          <view 
            class="history-tag"
            v-for="(item, index) in searchHistory"
            :key="index"
            @click="selectHistoryItem(item)"
          >
            {{ item }}
          </view>
        </view>
      </view>
    </view>

    <!-- 药品分类 -->
    <view class="category-section" v-if="!searchKeyword && !showSearchHistory">
      <view class="section-title">药品分类</view>
      <view class="category-grid">
        <view 
          class="category-item"
          v-for="category in drugCategories"
          :key="category.id"
          @click="selectCategory(category)"
        >
          <view class="category-icon" :style="{ backgroundColor: category.color }">
            <image :src="category.iconSrc" mode="aspectFit" class="icon-svg"></image>
          </view>
          <view class="category-name">{{ category.name }}</view>
          <view class="category-count">{{ category.count }}种</view>
        </view>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="results-section" v-if="searchKeyword || selectedCategory">
      <view class="results-header">
        <view class="results-info">
          <text v-if="searchKeyword">搜索"{{ searchKeyword }}"</text>
          <text v-else-if="selectedCategory">{{ selectedCategory.name }}</text>
          <text class="results-count">找到 {{ filteredDrugs.length }} 个结果</text>
        </view>
        <view class="sort-filter">
          <picker 
            :range="sortOptions" 
            :range-key="'label'"
            :value="selectedSort"
            @change="changeSortOption"
          >
            <view class="sort-btn">
              <text class="iconfont icon-sort"></text>
              {{ sortOptions[selectedSort].label }}
            </view>
          </picker>
        </view>
      </view>
      
      <view class="drug-list">
        <view 
          class="drug-item"
          v-for="drug in paginatedDrugs"
          :key="drug.id"
          @click="viewDrugDetail(drug)"
        >
          <view class="drug-image">
            <image :src="drug.image" class="drug-img" />
            <view class="prescription-badge" v-if="drug.prescription">
              处方药
            </view>
          </view>
          <view class="drug-info">
            <view class="drug-name">{{ drug.name }}</view>
            <view class="drug-spec">{{ drug.specification }}</view>
            <view class="drug-manufacturer">{{ drug.manufacturer }}</view>
            <view class="drug-indications">{{ drug.indications }}</view>
          </view>
          <view class="drug-actions">
            <view class="drug-price">¥{{ drug.price }}</view>
            <view class="action-buttons">
              <button 
                class="favorite-btn"
                :class="{ 'favorited': isFavorited(drug.id) }"
                @click.stop="toggleFavorite(drug)"
              >
                <text class="iconfont" :class="isFavorited(drug.id) ? 'icon-heart-filled' : 'icon-heart'"></text>
              </button>
            </view>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore" @click="loadMore">
          <text v-if="loading" class="iconfont icon-loading loading-icon"></text>
          {{ loading ? '加载中...' : '加载更多' }}
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="filteredDrugs.length === 0 && !loading">
          <image src="/static/images/empty-drugs.png" class="empty-image" />
          <view class="empty-text">没有找到相关药品</view>
          <button class="empty-btn" @click="clearSearch">
            重新搜索
          </button>
        </view>
      </view>
    </view>

    <!-- 我的收藏 -->
    <view class="favorites-section" v-if="!searchKeyword && !selectedCategory">
      <view class="section-header">
        <view class="section-title">我的收藏</view>
        <view class="more-link" @click="viewAllFavorites">
          查看全部 <text class="iconfont icon-arrow-right"></text>
        </view>
      </view>
      
      <view class="favorites-list" v-if="recentFavorites.length > 0">
        <view 
          class="favorite-item"
          v-for="drug in recentFavorites"
          :key="drug.id"
          @click="viewDrugDetail(drug)"
        >
          <image :src="drug.image" class="favorite-img" />
          <view class="favorite-info">
            <view class="favorite-name">{{ drug.name }}</view>
            <view class="favorite-spec">{{ drug.specification }}</view>
          </view>
          <view class="favorite-price">¥{{ drug.price }}</view>
        </view>
      </view>
      
      <view class="no-favorites" v-else>
        <text class="iconfont icon-heart"></text>
        <text class="no-favorites-text">暂无收藏药品</text>
      </view>
    </view>

    <!-- OCR识别选项 -->
    <uni-popup ref="ocrPopup" type="bottom" background-color="#ffffff">
      <view class="ocr-popup">
        <view class="popup-header">
          <view class="popup-title">药品识别</view>
          <view class="popup-close" @click="closeOCROptions">
            <text class="iconfont icon-close"></text>
          </view>
        </view>
        
        <view class="ocr-options">
          <view class="ocr-option" @click="takePhoto">
            <view class="option-icon camera-icon">
              <image src="/static/icons/拍照.svg" mode="aspectFit" class="icon-svg"></image>
            </view>
            <view class="option-text">
              <view class="option-title">拍照识别</view>
              <view class="option-desc">拍摄药盒或包装识别药品信息</view>
            </view>
          </view>
          
          <view class="ocr-option" @click="chooseImage">
            <view class="option-icon gallery-icon">
              <image src="/static/icons/相册.svg" mode="aspectFit" class="icon-svg"></image>
            </view>
            <view class="option-text">
              <view class="option-title">相册选择</view>
              <view class="option-desc">从相册选择药品图片进行识别</view>
            </view>
          </view>
        </view>
        
        <view class="ocr-tips">
          <view class="tips-title">识别小贴士：</view>
          <view class="tips-list">
            <text class="tip-item">• 确保药品包装清晰可见</text>
            <text class="tip-item">• 避免反光和阴影</text>
            <text class="tip-item">• 药品名称完整显示</text>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- OCR结果弹窗 -->
    <uni-popup ref="ocrResultPopup" type="center" background-color="#ffffff">
      <view class="ocr-result-popup">
        <view class="result-header">
          <view class="result-title">识别结果</view>
          <view class="result-close" @click="closeOCRResult">
            <text class="iconfont icon-close"></text>
          </view>
        </view>
        
        <view class="result-content" v-if="ocrResult">
          <view class="result-image">
            <image :src="ocrResult.image" class="ocr-img" />
          </view>
          
          <view class="result-info">
            <view class="info-row">
              <view class="confidence-bar">
                <view class="confidence-label">识别置信度</view>
                <view class="confidence-value">{{ (ocrResult.confidence * 100).toFixed(1) }}%</view>
              </view>
              <view class="service-info" v-if="ocrResult.serviceUsed">
                <text class="service-label">识别服务：</text>
                <text class="service-name">{{ getServiceDisplayName(ocrResult.serviceUsed) }}</text>
              </view>
            </view>
            <view class="confidence-progress">
              <view 
                class="progress-fill" 
                :style="{ width: (ocrResult.confidence * 100) + '%' }"
              ></view>
            </view>
          </view>
          
          <view class="recognized-text">
            <view class="text-label">识别文字：</view>
            <view class="text-content">{{ ocrResult.text }}</view>
          </view>

          <!-- 药品详细信息 -->
          <view class="drug-details" v-if="ocrResult.drugInfo && hasValidDrugInfo(ocrResult.drugInfo)">
            <view class="details-title">解析信息：</view>
            <view class="detail-item" v-if="ocrResult.drugInfo.name">
              <text class="detail-label">药品名称：</text>
              <text class="detail-value">{{ ocrResult.drugInfo.name }}</text>
            </view>
            <view class="detail-item" v-if="ocrResult.drugInfo.specification">
              <text class="detail-label">规格：</text>
              <text class="detail-value">{{ ocrResult.drugInfo.specification }}</text>
            </view>
            <view class="detail-item" v-if="ocrResult.drugInfo.manufacturer">
              <text class="detail-label">生产企业：</text>
              <text class="detail-value">{{ ocrResult.drugInfo.manufacturer }}</text>
            </view>
            <view class="detail-item" v-if="ocrResult.drugInfo.batchNumber">
              <text class="detail-label">批号：</text>
              <text class="detail-value">{{ ocrResult.drugInfo.batchNumber }}</text>
            </view>
            <view class="detail-item" v-if="ocrResult.drugInfo.expiryDate">
              <text class="detail-label">有效期：</text>
              <text class="detail-value">{{ ocrResult.drugInfo.expiryDate }}</text>
            </view>
            <view class="detail-item" v-if="ocrResult.drugInfo.approvalNumber">
              <text class="detail-label">批准文号：</text>
              <text class="detail-value">{{ ocrResult.drugInfo.approvalNumber }}</text>
            </view>
          </view>
          
          <view class="drug-matches" v-if="ocrResult.drugMatches && ocrResult.drugMatches.length > 0">
            <view class="matches-title">匹配药品：</view>
            <view 
              class="match-item"
              v-for="match in ocrResult.drugMatches"
              :key="match.drugId"
              @click="selectOCRMatch(match)"
            >
              <view class="match-name">{{ match.name }}</view>
              <view class="match-similarity">相似度 {{ (match.similarity * 100).toFixed(1) }}%</view>
            </view>
          </view>
        </view>
        
        <view class="result-actions">
          <button class="result-btn retry-btn" @click="retryOCR">
            <text class="iconfont icon-refresh"></text>
            重新识别
          </button>
          <button class="result-btn search-btn" @click="searchOCRText">
            <text class="iconfont icon-search"></text>
            搜索结果
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import ocrService from '../../services/ocrService.js'
import drugService from '../../services/drugService.js'

export default {
  name: 'DrugsPage',
  data() {
    return {
      searchKeyword: '',
      showSearchHistory: false,
      selectedCategory: null,
      selectedSort: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      ocrResult: null,
      
      // 实际数据
      allDrugs: [],
      totalDrugs: 0,
      hasMore: false,
      
      // 搜索历史
      searchHistory: ['阿莫西林', '布洛芬', '头孢克肟'],
      
      // 排序选项
      sortOptions: [
        { label: '综合排序', value: 'default' },
        { label: '价格从低到高', value: 'price_asc' },
        { label: '价格从高到低', value: 'price_desc' },
        { label: '按名称排序', value: 'name' }
      ],
      
      // 药品分类
      drugCategories: [],
      
      // 示例药品数据
      sampleDrugs: [
        {
          id: 'drug002',
          name: '布洛芬缓释胶囊',
          specification: '0.3g*10粒',
          manufacturer: '中美史克制药',
          price: 22.50,
          image: '/static/images/drug2.jpg',
          prescription: false,
          category: 'analgesics',
          indications: '用于缓解轻到中度疼痛',
          contraindications: '对布洛芬过敏者禁用',
          dosage: '成人一次0.3g，每12小时1次'
        }
      ]
    }
  },
  computed: {
    ...mapState('drugs', ['favorites', 'searchResults']),
    
    // 过滤后的药品列表
    filteredDrugs() {
      let drugs = this.allDrugs
      
      if (this.searchKeyword) {
        drugs = drugs.filter(drug => 
          drug.name.includes(this.searchKeyword) ||
          drug.indications.includes(this.searchKeyword) ||
          drug.manufacturer.includes(this.searchKeyword)
        )
      }
      
      if (this.selectedCategory) {
        drugs = drugs.filter(drug => drug.category === this.selectedCategory.id)
      }
      
      // 排序
      const sortOption = this.sortOptions[this.selectedSort]
      switch (sortOption.value) {
        case 'price_asc':
          drugs.sort((a, b) => a.price - b.price)
          break
        case 'price_desc':
          drugs.sort((a, b) => b.price - a.price)
          break
        case 'name':
          drugs.sort((a, b) => a.name.localeCompare(b.name))
          break
      }
      
      return drugs
    },
    
    // 分页后的药品列表
    paginatedDrugs() {
      return this.filteredDrugs.slice(0, this.currentPage * this.pageSize)
    },
    
    // 是否有更多数据
    hasMore() {
      return this.paginatedDrugs.length < this.filteredDrugs.length
    },
    
    // 最近收藏的药品
    recentFavorites() {
      return this.favorites.slice(0, 3)
    }
  },
  onLoad() {
    this.initPage()
  },
  onShow() {
    this.refreshFavorites()
  },
  methods: {
    ...mapActions('drugs', ['searchDrug', 'addToFavorites', 'removeFromFavorites', 'ocrRecognize']),

    // 初始化页面
    async initPage() {
      this.loadSearchHistory()
      this.refreshFavorites()
      await this.loadDrugCategories()
      await this.loadInitialDrugs()
    },

    // 搜索输入
    onSearchInput() {
      this.showSearchHistory = this.searchKeyword.length === 0
      if (this.searchKeyword.length > 0) {
        this.selectedCategory = null
      }
    },

    // 搜索药品
    async searchDrugs() {
      if (!this.searchKeyword.trim()) return
      
      this.showSearchHistory = false
      this.addToSearchHistory(this.searchKeyword)
      this.currentPage = 1
      this.loading = true
      
      try {
        const response = await drugService.searchDrugs({
          q: this.searchKeyword.trim(),
          page: this.currentPage,
          limit: this.pageSize,
          sortBy: this.getSortField(),
          sortOrder: this.getSortOrder(),
          inStock: true
        })
        
        if (response && response.success) {
          this.allDrugs = response.data.drugs || []
          this.totalDrugs = response.data.pagination?.total || 0
          this.hasMore = response.data.pagination?.page < response.data.pagination?.pages
        }
        
      } catch (error) {
        console.error('搜索失败:', error)
        uni.showToast({
          title: '搜索失败，请稍后重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 清空搜索
    clearSearch() {
      this.searchKeyword = ''
      this.showSearchHistory = false
      this.selectedCategory = null
      this.currentPage = 1
    },

    // 选择搜索历史
    selectHistoryItem(item) {
      this.searchKeyword = item
      this.searchDrugs()
    },

    // 添加到搜索历史
    addToSearchHistory(keyword) {
      if (this.searchHistory.includes(keyword)) {
        this.searchHistory = this.searchHistory.filter(item => item !== keyword)
      }
      this.searchHistory.unshift(keyword)
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10)
      }
      this.saveSearchHistory()
    },

    // 清空搜索历史
    clearSearchHistory() {
      this.searchHistory = []
      this.saveSearchHistory()
    },

    // 保存搜索历史
    saveSearchHistory() {
      uni.setStorageSync('drugSearchHistory', this.searchHistory)
    },

    // 加载搜索历史
    loadSearchHistory() {
      const history = uni.getStorageSync('drugSearchHistory')
      if (history && Array.isArray(history)) {
        this.searchHistory = history
      }
    },

    // 选择分类
    async selectCategory(category) {
      this.selectedCategory = category
      this.searchKeyword = ''
      this.showSearchHistory = false
      this.currentPage = 1
      this.loading = true
      
      try {
        const response = await drugService.getDrugsByCategory(category.id, {
          page: this.currentPage,
          limit: this.pageSize,
          sortBy: this.getSortField(),
          sortOrder: this.getSortOrder()
        })
        
        if (response && response.success) {
          this.allDrugs = response.data.drugs || []
          this.totalDrugs = response.data.pagination?.total || 0
          this.hasMore = response.data.pagination?.page < response.data.pagination?.pages
        }
        
      } catch (error) {
        console.error('获取分类药品失败:', error)
        uni.showToast({
          title: '加载失败，请稍后重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 改变排序
    changeSortOption(e) {
      this.selectedSort = e.detail.value
      this.currentPage = 1
    },

    // 加载更多
    loadMore() {
      if (this.loading || !this.hasMore) return
      
      this.loading = true
      
      // 模拟加载延迟
      setTimeout(() => {
        this.currentPage++
        this.loading = false
      }, 1000)
    },

    // 查看药品详情
    viewDrugDetail(drug) {
      uni.navigateTo({
        url: `/pages/drugs/detail?id=${drug.drugId || drug.id}`
      })
    },

    // 是否已收藏
    isFavorited(drugId) {
      return this.favorites.some(fav => fav.id === drugId || fav.drugId === drugId)
    },

    // 切换收藏状态
    async toggleFavorite(drug) {
      try {
        const drugId = drug.drugId || drug.id
        if (this.isFavorited(drugId)) {
          await this.removeFromFavorites(drugId)
          uni.showToast({
            title: '已取消收藏',
            icon: 'success'
          })
        } else {
          await this.addToFavorites(drug)
          uni.showToast({
            title: '已添加收藏',
            icon: 'success'
          })
        }
      } catch (error) {
        console.error('操作失败:', error)
        uni.showToast({
          title: '操作失败',
          icon: 'error'
        })
      }
    },

    // 查看全部收藏
    viewAllFavorites() {
      uni.navigateTo({
        url: '/pages/drugs/favorites'
      })
    },

    // 刷新收藏列表
    refreshFavorites() {
      // 实际项目中从store获取
    },

    // 加载药品分类
    async loadDrugCategories() {
      try {
        const response = await drugService.getDrugCategories()
        
        if (response && response.success) {
          const categoryIcons = {
            'antibiotics': { icon: 'icon-medicine', iconSrc: '/static/icons/抗生素指南.svg', color: '#1890ff' },
            'analgesics': { icon: 'icon-capsule', iconSrc: '/static/icons/药事服务.svg', color: '#52c41a' },
            'cold': { icon: 'icon-pill', iconSrc: '/static/icons/药事服务.svg', color: '#fa8c16' },
            'digestive': { icon: 'icon-tablet', iconSrc: '/static/icons/消化内科.svg', color: '#eb2f96' },
            'cardiovascular': { icon: 'icon-heart', iconSrc: '/static/icons/药事服务.svg', color: '#f5222d' },
            'respiratory': { icon: 'icon-wind', iconSrc: '/static/icons/药事服务.svg', color: '#722ed1' },
            'other': { icon: 'icon-medicine', iconSrc: '/static/icons/药事服务.svg', color: '#666666' }
          }
          
          this.drugCategories = response.data.map(cat => ({
            id: cat.id,
            name: cat.name,
            count: cat.count,
            ...(categoryIcons[cat.id] || categoryIcons.other)
          }))
        }
        
      } catch (error) {
        console.error('加载药品分类失败:', error)
      }
    },

    // 加载初始药品数据
    async loadInitialDrugs() {
      this.loading = true
      
      try {
        const response = await drugService.searchDrugs({
          page: 1,
          limit: this.pageSize,
          inStock: true,
          sortBy: 'rating',
          sortOrder: 'desc'
        })
        
        if (response && response.success) {
          this.allDrugs = response.data.drugs || []
          this.totalDrugs = response.data.pagination?.total || 0
          this.hasMore = response.data.pagination?.page < response.data.pagination?.pages
        }
        
      } catch (error) {
        console.error('加载初始数据失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 获取排序字段
    getSortField() {
      const sortOption = this.sortOptions[this.selectedSort]
      switch (sortOption.value) {
        case 'price_asc':
        case 'price_desc':
          return 'price'
        case 'name':
          return 'name'
        default:
          return 'rating'
      }
    },

    // 获取排序顺序
    getSortOrder() {
      const sortOption = this.sortOptions[this.selectedSort]
      switch (sortOption.value) {
        case 'price_asc':
        case 'name':
          return 'asc'
        case 'price_desc':
          return 'desc'
        default:
          return 'desc'
      }
    },

    // 显示OCR选项
    showOCROptions() {
      this.$refs.ocrPopup.open()
    },

    // 关闭OCR选项
    closeOCROptions() {
      this.$refs.ocrPopup.close()
    },

    // 拍照识别
    takePhoto() {
      this.closeOCROptions()
      
      uni.chooseImage({
        count: 1,
        sourceType: ['camera'],
        success: (res) => {
          this.processOCRImage(res.tempFilePaths[0])
        },
        fail: (error) => {
          console.error('拍照失败:', error)
          uni.showToast({
            title: '拍照失败',
            icon: 'error'
          })
        }
      })
    },

    // 选择图片
    chooseImage() {
      this.closeOCROptions()
      
      uni.chooseImage({
        count: 1,
        sourceType: ['album'],
        success: (res) => {
          this.processOCRImage(res.tempFilePaths[0])
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
          uni.showToast({
            title: '选择图片失败',
            icon: 'error'
          })
        }
      })
    },

    // 处理OCR图片
    async processOCRImage(imagePath) {
      try {
        uni.showLoading({ title: '识别中...', mask: true })
        
        // 调用OCR服务进行药品识别
        const result = await ocrService.recognizeDrug(imagePath, {
          parallel: false, // 可根据需要启用并行识别
          extraData: {
            deviceType: 'wxapp',
            userId: this.$store.getters['auth/userInfo']?.id
          }
        })
        
        if (result.success && result.data) {
          // 构建OCR结果数据
          this.ocrResult = {
            image: imagePath,
            confidence: result.data.confidence || 0,
            text: result.data.text || '',
            originalFile: result.data.originalFile,
            serviceUsed: result.data.serviceUsed,
            drugInfo: result.data.drugInfo || {},
            // 将解析的药品信息转换为匹配项格式
            drugMatches: this.buildDrugMatches(result.data.drugInfo, result.data.text)
          }
          
          // 显示识别结果
          this.$refs.ocrResultPopup.open()
          
          // 记录识别成功
          console.log('OCR识别成功:', result.message)
          
        } else {
          // OCR识别失败，显示错误信息
          throw new Error(result.error || 'OCR识别失败')
        }
        
      } catch (error) {
        console.error('OCR识别失败:', error)
        
        // 显示详细错误信息
        uni.showModal({
          title: '识别失败',
          content: error.message || '图片识别失败，请确保图片清晰并包含药品信息',
          showCancel: true,
          cancelText: '取消',
          confirmText: '重试',
          success: (res) => {
            if (res.confirm) {
              // 重新选择图片
              this.showOCROptions()
            }
          }
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 构建药品匹配项
    buildDrugMatches(drugInfo, text) {
      const matches = []
      
      // 如果解析出了药品名称，创建匹配项
      if (drugInfo.name) {
        matches.push({
          drugId: `ocr_${Date.now()}`, // 临时ID
          name: drugInfo.name,
          specification: drugInfo.specification || '',
          manufacturer: drugInfo.manufacturer || '',
          similarity: 0.9, // 基于OCR置信度的相似度
          source: 'ocr_parsed'
        })
      }
      
      // 如果没有解析出药品名称，但有识别文字，使用原文
      if (matches.length === 0 && text.trim()) {
        matches.push({
          drugId: `text_${Date.now()}`,
          name: text.trim(),
          specification: '',
          manufacturer: '',
          similarity: 0.7,
          source: 'ocr_text'
        })
      }
      
      return matches
    },

    // 关闭OCR结果
    closeOCRResult() {
      this.$refs.ocrResultPopup.close()
      this.ocrResult = null
    },

    // 重新识别
    retryOCR() {
      this.retryOCRWithOptions()
    },

    // 搜索OCR文字
    searchOCRText() {
      if (this.ocrResult && this.ocrResult.text) {
        this.searchKeyword = this.ocrResult.text
        this.closeOCRResult()
        this.searchDrugs()
      }
    },

    // 选择OCR匹配项
    selectOCRMatch(match) {
      this.closeOCRResult()
      
      // 如果是OCR解析的结果，使用药品名称搜索
      if (match.source === 'ocr_parsed' || match.source === 'ocr_text') {
        this.searchKeyword = match.name
        this.searchDrugs()
      } else {
        this.viewDrugDetail({ id: match.drugId })
      }
    },

    // 获取OCR服务显示名称
    getServiceDisplayName(serviceType) {
      const serviceNames = {
        'baidu': '百度AI',
        'aliyun': '阿里云',
        'tesseract': 'Tesseract',
        'ppocr': 'PP-OCR',
        'mock': '演示模式'
      }
      return serviceNames[serviceType] || '未知服务'
    },

    // 检查是否有有效的药品信息
    hasValidDrugInfo(drugInfo) {
      if (!drugInfo) return false
      
      // 检查是否至少有一个字段有值
      return !!(
        drugInfo.name ||
        drugInfo.specification ||
        drugInfo.manufacturer ||
        drugInfo.batchNumber ||
        drugInfo.expiryDate ||
        drugInfo.approvalNumber
      )
    },

    // 重新识别（支持高级选项）
    retryOCRWithOptions() {
      this.closeOCRResult()
      
      // 显示高级识别选项
      uni.showActionSheet({
        itemList: [
          '重新拍照识别',
          '重新选择图片',
          '并行识别模式（更准确）'
        ],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              this.takePhoto()
              break
            case 1:
              this.chooseImage()
              break
            case 2:
              // 使用并行识别模式
              this.showOCROptionsWithParallel()
              break
          }
        }
      })
    },

    // 显示并行识别选项
    showOCROptionsWithParallel() {
      uni.showActionSheet({
        itemList: ['拍照识别（并行模式）', '相册选择（并行模式）'],
        success: (res) => {
          const useParallel = true
          if (res.tapIndex === 0) {
            this.takePhotoWithOptions({ parallel: useParallel })
          } else {
            this.chooseImageWithOptions({ parallel: useParallel })
          }
        }
      })
    },

    // 带选项的拍照
    takePhotoWithOptions(options = {}) {
      uni.chooseImage({
        count: 1,
        sourceType: ['camera'],
        success: (res) => {
          this.processOCRImageWithOptions(res.tempFilePaths[0], options)
        },
        fail: (error) => {
          console.error('拍照失败:', error)
          uni.showToast({
            title: '拍照失败',
            icon: 'error'
          })
        }
      })
    },

    // 带选项的选择图片
    chooseImageWithOptions(options = {}) {
      uni.chooseImage({
        count: 1,
        sourceType: ['album'],
        success: (res) => {
          this.processOCRImageWithOptions(res.tempFilePaths[0], options)
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
          uni.showToast({
            title: '选择图片失败',
            icon: 'error'
          })
        }
      })
    },

    // 带选项的OCR处理
    async processOCRImageWithOptions(imagePath, options = {}) {
      try {
        const loadingTitle = options.parallel ? '并行识别中...' : '识别中...'
        uni.showLoading({ title: loadingTitle, mask: true })
        
        // 调用OCR服务
        const result = await ocrService.recognizeDrug(imagePath, {
          parallel: options.parallel || false,
          extraData: {
            deviceType: 'wxapp',
            userId: this.$store.getters['auth/userInfo']?.id,
            ...options.extraData
          }
        })
        
        if (result.success && result.data) {
          this.ocrResult = {
            image: imagePath,
            confidence: result.data.confidence || 0,
            text: result.data.text || '',
            originalFile: result.data.originalFile,
            serviceUsed: result.data.serviceUsed,
            drugInfo: result.data.drugInfo || {},
            recognitionMode: result.data.recognitionMode || 'single',
            drugMatches: this.buildDrugMatches(result.data.drugInfo, result.data.text)
          }
          
          this.$refs.ocrResultPopup.open()
          console.log('OCR识别成功:', result.message)
          
        } else {
          throw new Error(result.error || 'OCR识别失败')
        }
        
      } catch (error) {
        console.error('OCR识别失败:', error)
        uni.showModal({
          title: '识别失败',
          content: error.message || '图片识别失败，请确保图片清晰并包含药品信息',
          showCancel: true,
          cancelText: '取消',
          confirmText: '重试',
          success: (res) => {
            if (res.confirm) {
              this.showOCROptions()
            }
          }
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.drugs-container {
  min-height: 100vh;
  background: #f5f5f5;
}

// 搜索区域
.search-section {
  background: white;
  padding: 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.search-box {
  display: flex;
  gap: 16rpx;
}

.search-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 48rpx;
  padding: 0 32rpx;
}

.search-icon {
  font-size: 32rpx;
  color: #bfbfbf;
  margin-right: 16rpx;
}

.search-input {
  flex: 1;
  padding: 24rpx 0;
  font-size: 28rpx;
  color: #262626;
  background: transparent;
  border: none;
}

.clear-btn {
  padding: 8rpx;
  
  .iconfont {
    font-size: 24rpx;
    color: #bfbfbf;
  }
}

.ocr-btn {
  padding: 24rpx 32rpx;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 48rpx;
  font-size: 26rpx;
  display: flex;
  align-items: center;
  
  .iconfont {
    font-size: 28rpx;
    margin-right: 8rpx;
  }
}

.search-history {
  margin-top: 32rpx;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.history-title {
  font-size: 28rpx;
  color: #262626;
}

.clear-history {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #f5222d;
  
  .iconfont {
    font-size: 20rpx;
    margin-right: 8rpx;
  }
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.history-tag {
  padding: 12rpx 24rpx;
  background: #f0f0f0;
  border-radius: 32rpx;
  font-size: 24rpx;
  color: #595959;
}

// 分类区域
.category-section {
  background: white;
  margin: 16rpx 32rpx;
  border-radius: 24rpx;
  padding: 32rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #262626;
  margin-bottom: 24rpx;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 32rpx 16rpx;
  background: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.12);
  }
}

.category-icon {
  width: 88rpx;
  height: 88rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
  
  .icon-svg {
    width: 48rpx;
    height: 48rpx;
    filter: brightness(0) invert(1);
  }
  
  .iconfont {
    font-size: 36rpx;
    color: white;
  }
}

.category-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #262626;
  margin-bottom: 8rpx;
  text-align: center;
}

.category-count {
  font-size: 24rpx;
  color: #666666;
  font-weight: 500;
}

// 搜索结果
.results-section {
  padding: 0 32rpx;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.results-info {
  flex: 1;
}

.results-count {
  display: block;
  font-size: 24rpx;
  color: #8c8c8c;
  margin-top: 8rpx;
}

.sort-filter {
  .sort-btn {
    display: flex;
    align-items: center;
    padding: 12rpx 24rpx;
    background: #f5f5f5;
    border-radius: 24rpx;
    font-size: 24rpx;
    color: #595959;
    
    .iconfont {
      font-size: 20rpx;
      margin-right: 8rpx;
    }
  }
}

.drug-list {
  background: white;
  border-radius: 24rpx;
  overflow: hidden;
}

.drug-item {
  display: flex;
  padding: 24rpx;
  border-bottom: 2rpx solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
}

.drug-image {
  position: relative;
  margin-right: 24rpx;
  
  .drug-img {
    width: 120rpx;
    height: 120rpx;
    border-radius: 12rpx;
  }
}

.prescription-badge {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  background: #f5222d;
  color: white;
  font-size: 18rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
}

.drug-info {
  flex: 1;
}

.drug-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #262626;
  margin-bottom: 8rpx;
}

.drug-spec {
  font-size: 24rpx;
  color: #8c8c8c;
  margin-bottom: 8rpx;
}

.drug-manufacturer {
  font-size: 22rpx;
  color: #bfbfbf;
  margin-bottom: 12rpx;
}

.drug-indications {
  font-size: 22rpx;
  color: #595959;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.drug-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
  margin-left: 16rpx;
}

.drug-price {
  font-size: 28rpx;
  font-weight: 500;
  color: #f5222d;
}

.action-buttons {
  display: flex;
  gap: 8rpx;
}

.favorite-btn {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background: #f5f5f5;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .iconfont {
    font-size: 24rpx;
    color: #bfbfbf;
  }
  
  &.favorited {
    background: #fff2f0;
    
    .iconfont {
      color: #f5222d;
    }
  }
}

.load-more {
  text-align: center;
  padding: 48rpx;
  color: #8c8c8c;
  font-size: 26rpx;
}

.loading-icon {
  animation: rotate 1s linear infinite;
  margin-right: 12rpx;
}

// 收藏区域
.favorites-section {
  background: white;
  margin: 16rpx 32rpx;
  border-radius: 24rpx;
  padding: 32rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.more-link {
  font-size: 24rpx;
  color: #1890ff;
  display: flex;
  align-items: center;
  
  .iconfont {
    font-size: 20rpx;
    margin-left: 8rpx;
  }
}

.favorites-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.favorite-item {
  display: flex;
  align-items: center;
  padding: 16rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
}

.favorite-img {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  margin-right: 16rpx;
}

.favorite-info {
  flex: 1;
}

.favorite-name {
  font-size: 26rpx;
  color: #262626;
  margin-bottom: 8rpx;
}

.favorite-spec {
  font-size: 22rpx;
  color: #8c8c8c;
}

.favorite-price {
  font-size: 24rpx;
  color: #f5222d;
  font-weight: 500;
}

.no-favorites {
  text-align: center;
  padding: 48rpx;
  color: #bfbfbf;
  
  .iconfont {
    font-size: 64rpx;
    margin-bottom: 16rpx;
    display: block;
  }
}

// OCR弹窗
.ocr-popup {
  border-radius: 24rpx 24rpx 0 0;
  max-height: 80vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.popup-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #262626;
}

.popup-close {
  padding: 16rpx;
  color: #8c8c8c;
  
  .iconfont {
    font-size: 32rpx;
  }
}

.ocr-options {
  padding: 32rpx;
}

.ocr-option {
  display: flex;
  align-items: center;
  padding: 32rpx;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &:active {
    background: #f5f5f5;
  }
}

.option-icon {
  width: 88rpx;
  height: 88rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
  
  .icon-svg {
    width: 40rpx;
    height: 40rpx;
    filter: brightness(0) invert(1);
  }
  
  .iconfont {
    font-size: 36rpx;
    color: white;
  }
  
  &.camera-icon {
    background: #1890ff;
  }
  
  &.gallery-icon {
    background: #52c41a;
  }
}

.option-text {
  flex: 1;
}

.option-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #262626;
  margin-bottom: 8rpx;
  text-align: center;
}

.option-desc {
  font-size: 24rpx;
  color: #8c8c8c;
  line-height: 1.4;
  text-align: center;
}

.ocr-tips {
  padding: 32rpx;
  background: #f0f9ff;
  border-top: 2rpx solid #f5f5f5;
}

.tips-title {
  font-size: 26rpx;
  font-weight: 500;
  color: #1890ff;
  margin-bottom: 16rpx;
}

.tips-list {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.tip-item {
  font-size: 24rpx;
  color: #595959;
  line-height: 1.4;
}

// OCR结果弹窗
.ocr-result-popup {
  width: 640rpx;
  max-height: 80vh;
  border-radius: 24rpx;
  overflow: hidden;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.result-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #262626;
}

.result-close {
  padding: 16rpx;
  color: #8c8c8c;
  
  .iconfont {
    font-size: 32rpx;
  }
}

.result-content {
  padding: 32rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.result-image {
  text-align: center;
  margin-bottom: 32rpx;
  
  .ocr-img {
    width: 200rpx;
    height: 200rpx;
    border-radius: 16rpx;
  }
}

.result-info {
  margin-bottom: 32rpx;
}

.confidence-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.confidence-label {
  font-size: 26rpx;
  color: #262626;
}

.confidence-value {
  font-size: 26rpx;
  font-weight: 500;
  color: #52c41a;
}

.confidence-progress {
  height: 8rpx;
  background: #f5f5f5;
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #52c41a 0%, #73d13d 100%);
  transition: width 0.3s ease;
}

.recognized-text {
  margin-bottom: 32rpx;
}

.text-label {
  font-size: 26rpx;
  color: #8c8c8c;
  margin-bottom: 12rpx;
}

.text-content {
  font-size: 28rpx;
  color: #262626;
  line-height: 1.5;
  padding: 16rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.drug-matches {
  .matches-title {
    font-size: 26rpx;
    color: #8c8c8c;
    margin-bottom: 16rpx;
  }
}

.match-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx;
  background: #f0f9ff;
  border-radius: 12rpx;
  margin-bottom: 12rpx;
  border: 2rpx solid #91d5ff;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.match-name {
  font-size: 26rpx;
  color: #1890ff;
  font-weight: 500;
}

.match-similarity {
  font-size: 24rpx;
  color: #52c41a;
}

.result-actions {
  display: flex;
  gap: 16rpx;
  padding: 32rpx;
  border-top: 2rpx solid #f5f5f5;
}

.result-btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 16rpx;
  font-size: 26rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  
  .iconfont {
    font-size: 24rpx;
    margin-right: 12rpx;
  }
  
  &.retry-btn {
    background: #f5f5f5;
    color: #595959;
  }
  
  &.search-btn {
    background: #1890ff;
    color: white;
  }
}

// 空状态
.empty-state {
  text-align: center;
  padding: 120rpx 32rpx;
}

.empty-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 32rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #8c8c8c;
  margin-bottom: 48rpx;
}

.empty-btn {
  padding: 24rpx 48rpx;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 48rpx;
  font-size: 26rpx;
}

// 动画
@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// OCR结果弹窗新增样式
.info-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24rpx;
}

.confidence-bar {
  flex: 1;
}

.service-info {
  flex-shrink: 0;
  text-align: right;
  font-size: 24rpx;
  
  .service-label {
    color: #8c8c8c;
  }
  
  .service-name {
    color: #1890ff;
    font-weight: 500;
    margin-left: 8rpx;
  }
}

.drug-details {
  margin-top: 32rpx;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  
  .details-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #262626;
    margin-bottom: 20rpx;
    padding-bottom: 12rpx;
    border-bottom: 2rpx solid #e6f7ff;
  }
}

.detail-item {
  display: flex;
  margin-bottom: 16rpx;
  font-size: 26rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .detail-label {
    color: #8c8c8c;
    width: 160rpx;
    flex-shrink: 0;
  }
  
  .detail-value {
    color: #262626;
    flex: 1;
    font-weight: 500;
  }
}

// OCR按钮优化
.result-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx 32rpx;
  border-radius: 16rpx;
  font-size: 26rpx;
  border: none;
  
  .iconfont {
    font-size: 28rpx;
    margin-right: 8rpx;
  }
}

.retry-btn {
  background: #f5f5f5;
  color: #595959;
  
  &:active {
    background: #e6e6e6;
  }
}

.search-btn {
  background: #1890ff;
  color: white;
  
  &:active {
    background: #096dd9;
  }
}

// 匹配项显示优化
.match-item {
  padding: 20rpx 24rpx;
  margin-bottom: 16rpx;
  background: white;
  border-radius: 12rpx;
  border: 2rpx solid #f0f0f0;
  
  &:active {
    background: #f8f9fa;
    border-color: #1890ff;
  }
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .match-name {
    font-size: 28rpx;
    color: #262626;
    font-weight: 500;
    margin-bottom: 8rpx;
  }
  
  .match-similarity {
    font-size: 24rpx;
    color: #1890ff;
  }
}
</style>